package solution2;

public class Solution2 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode r1 = l1;
        ListNode r2 = l2;
        ListNode temp = new ListNode(0);
        ListNode root = temp;
        int carry = 0;
        while (r1 != null && r2 != null) {
            temp.next = new ListNode((r1.val + r2.val + carry) % 10);
            carry = (r1.val + r2.val +carry ) / 10;
            temp = temp.next;
            r1 = r1.next;
            r2 = r2.next;
        }

        while (r1 != null) {
            temp.next = new ListNode((r1.val + carry) % 10);
            carry = (r1.val +carry ) / 10;
            temp = temp.next;
            r1 = r1.next;
        }
        while (r2 != null) {
            temp.next = new ListNode((r2.val + carry) % 10);
            carry = (r2.val +carry ) / 10;
            temp = temp.next;
            r2 = r2.next;
        }
        if (carry != 0) {
            temp.next = new ListNode(carry);
        }
        return root.next;
    }
}
